import tkinter as tk
from tkinter.messagebox import showinfo
import windnd
import os
import html
import urllib.request
import time
import string

cur_tab = 0

color_dic = {"#B2B2FE": "purple",
             "#ADD2FF": "blue",
             "#FFFFAA": "",
             "#BEFFBE": "green",
             "#ADD2FF": "blue",
             "#FFAABE": "red",
             "#FFFF00": "yellow",
             "#00FF00": "green",
             "#00BEFF": "blue",
             "#FF0000": "red",
             "#FF8000": "yellow",
             "#008040": "green",
             "#003EB3": "blue",
             "#CF1B11": "red",
             "#7F7F7F": "",
             "#DADADA": "",
             "#B4B4B4": "",
             "#C39DE0": "purple"}


dir_name = None


def mm_format(mm_fpath):
    global dir_name
    try:
        dir_name = path + "/mmformat" + str(int(time.time()))
        if not os.path.exists(dir_name):
            os.makedirs(dir_name)

        f = open(mm_fpath, 'r')
        alllines = f.readlines()
        f.close()
        f = open(mm_fpath, 'w+')
        for eachline in alllines:
            f.writelines(eachline.replace(">", ">\n"))
        f.close()

        fnew = open(dir_name + '/temp.mm', 'w+')
        with open(mm_fpath, 'r') as f:
            line = f.readline()
            while line:
                data = line.strip()
                if len(data) != 0:
                    fnew.write(line)
                line = f.readline()
        f.close()
        fnew.close()
        mm_trans(dir_name + "/temp.mm")
        return True
    except Exception as e:
        print(e)
        return False


def mm_trans(mm_fpath):
    global cur_tab
    fnew = open(dir_name + '/new.mm', 'w+', encoding="utf-8")
    fnew.write("<map>\n")
    f = open(mm_fpath, 'r')
    lines = f.readlines()
    first_flag = True
    top_flag = False
    for i in range(len(lines) - 2):
        line = lines[i].split("\n")[0]
        # print(line)
        type = check_type(line)
        if type != "node" and type != "</node>":
            continue
        if type == "</node>":
            newline = ("    ") * cur_tab + "</node>\n"
            fnew.write(newline)
            cur_tab -= 1
        else:
            if top_flag == False:
                top_flag = True
                continue
            else:
                # print(line)
                cur_tab += 1
                color, index = find_edge(i, lines)
                newele, linest = creat_ele(line, color, first_flag)
                i = index
                newline = ("    ") * cur_tab + newele + "\n"
                # if linest != False:
                fnew.write(newline)
                if first_flag:
                    first_flag = False
    fnew.write("</map>\n")
    f.close()


def check_type(line):
    if line == "</node>":
        return line
    return line.split("<")[1].split(" ")[0]


def find_edge(index, lines):
    for i in range(index, len(lines)):
        line = lines[i].split("\n")[0]
        if line.split(" ")[0] != "<edge":
            continue
        # print("color: " + line)
        return line.split("COLOR=\"")[1].split("\"")[0], i


def creat_ele(line, color, first_flag):
    TEXT = ""
    ID = ""
    try:
        TEXT = html.unescape(line.split("TEXT=\"")[1].split("\"")[
                             0]).replace('\n', " - ").replace("\"", "&quot;")
        TEXT = TEXT.strip(string.punctuation)
        if TEXT[-1] == '。':
            TEXT = TEXT[:-1]
        ID = line.split("ID=\"")[1].split("\"")[0]

    except:
        TEXT = ""
        ID = ""

    color_span = color_dic[color]
    span_class = ""
    if color_span != "":
        span_class = "class=\" text-color-" + color_span + "\""
    mubu_text = urllib.parse.quote(
        "<span " + span_class + " >" + TEXT + "</span>", safe="=/,+:")
    # mubu_text = "<span " + span_class + " >" + TEXT + "</span>"
    if first_flag:
        newele = '<node ID="root" TEXT="' + TEXT + '">'
    else:
        newele = '<node TEXT="' + TEXT + '" ID="' + ID + \
            '" _mubu_text="' + mubu_text + '" STYLE="fork">'
    return newele, TEXT != ""


ori = res = path = None


def dragged_files(files):
    global ori, res, path
    ori = str(files[0].decode('gbk'))
    (file, ext) = os.path.splitext(ori)
    if ext != '.mm':
        showinfo("错误", "格式不正确")
        return
    (path, filename) = os.path.split(ori)
    res = file + "format" + str(int(time.time())) + ".mm"
    st_defalut()
    entry1.delete(0, "end")
    entry1.insert(0, ori)
    # entry2.delete(0, "end")
    # entry2.insert(0, res)

entry1 = entry2 = st = b = None


def st_defalut():
    st.config(text='还未转换')
    st.config(fg="#0000CD")


def st_process():
    st.config(text='正在转换')
    st.config(fg="#DA70D6")


def st_error():
    st.config(text='转换失败')
    st.config(fg="#DC143C")


def st_success():
    st.config(text='转换成功')
    st.config(fg="#228B22")


def init_tk():
    global entry1, entry2, st
    rootWindow = tk.Tk()
    rootWindow.title('FreeMind转幕布')
    width = 380
    height = 80
    screenwidth = rootWindow.winfo_screenwidth()
    screenheight = rootWindow.winfo_screenheight()
    size_geo = '%dx%d+%d+%d' % (width, height,
                                (screenwidth-width)/2, (screenheight-height)/2)
    rootWindow.geometry(size_geo)
    rootWindow.resizable(0, 0)
    tk.Label(rootWindow, text="原文件位置").grid(row=0, sticky='w')
    tk.Label(rootWindow, text="").grid(row=1, sticky='w')
    entry1 = tk.Entry(rootWindow)
    entry1.insert(0, "请将文件拖到此处")
    entry1.grid(row=0, column=1, padx=8, ipadx=50)
    # entry2 = tk.Entry(rootWindow)
    # entry2.grid(row=1, column=1, padx=8, ipadx=50)
    windnd.hook_dropfiles(entry1, func=dragged_files)
    st = tk.Label(rootWindow, text="还未转换", fg='#0000CD')
    st.grid(row=2, sticky='w')
    b = tk.Button(rootWindow, text="开始转换", command=format_main)
    b.grid(row=2, column=1, sticky='e')
    rootWindow.mainloop()


def format_main():
    st_process()
    if mm_format(ori):
        st_success()
    else:
        st_error()
    return


if __name__ == '__main__':
    init_tk()